﻿/**
 * @Author: NieQiang
 * @User: CAPTAIN
 * @CreateTime: 2023-8-29
 * @Desc: 图片重组；这里的重组方法，后台返回的结果是自定义的，若用户用原作者写的springboot的那套只需将代码中
 * 第9行和第24行替换
 **/
export function drawBgImage(data, canvasId, imgId, delay){
  // if (!data.data || !data.data.shuffle) {
  if (!data.data || !data.data.viewData.shuffle) {
    return;
  }
  let img = document.getElementById(imgId);
  if (img.width == 0 || img.height == 0) {
    setTimeout(()=>{drawBgImage(data, canvasId, imgId, delay)}, 50);
    return;
  }

  let c = document.getElementById(canvasId);
  let ctx = c.getContext("2d");
  c.width = img.width;
  c.height = img.height;

  // const shuffle = data.data.shuffle;
  const shuffle = data.data.viewData.shuffle;
  const sourceImageWidth = data.backgroundImageWidth;
  const sourceImageHeight = data.backgroundImageHeight;
  const canvasImageWidth = c.width;
  const canvasImageHeight = c.height;
  const xNum = shuffle.x;
  const yNum = shuffle.y;
  const pos = shuffle.pos;

  const sourceBlockX = sourceImageWidth / xNum;
  const sourceBlockY = sourceImageHeight / yNum;
  const blockX = canvasImageWidth / xNum;
  const blockY = canvasImageHeight / yNum;

  const sourceImageBlocks = [];
  const imageBlocks = [];
  for (let i = 0; i < yNum; i++) {
    for (let o = 0; o < xNum; o++) {
      sourceImageBlocks.push({
        startX: Math.floor(o * sourceBlockX),
        startY: Math.floor(i * sourceBlockY)
      });
      imageBlocks.push({
        startX: Math.round(o * blockX),
        startY: Math.round(i * blockY)
      });
    }
  }
  const evalFun = []
  for (let i = 0; i < pos.length; i++) {
    const p = pos[i]
    const sourceBlock = sourceImageBlocks[p];
    const block = imageBlocks[i];
    evalFun.push(() => {
      ctx.drawImage(img, sourceBlock.startX, sourceBlock.startY, sourceBlockX, sourceBlockY, block.startX, block.startY, blockX, blockY);
    });
  }
  evalFun.sort((a, b) => {
    return Math.random() > .5 ? -1 : 1;
  });
  for (let i = 0; i < evalFun.length; i++) {
    let fun = evalFun[i]
    if (delay > 0) {
      setTimeout(fun, (i + 1) * delay);
    } else {
      fun();
    }
  }
}
